﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Data.Common;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;

namespace BLL
{


    /// <summary>
    /// Summary description for FormatToJson
    /// </summary>
    public class FormatToJson
    {
        public FormatToJson()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        /// <summary> 
        /// List转成json 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="jsonName"></param> 
        /// <param name="list"></param> 
        /// <returns></returns> 
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = list[0].GetType().Name;
            Json.Append("{\"" + jsonName + "\":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        Type type = pi[j].GetValue(list[i], null).GetType();
                        Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
                        if (j < pi.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        public static string ListToJsonXP<T>(IList<T> list)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        Type type = pi[j].GetValue(list[i], null).GetType();
                        Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
                        if (j < pi.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }






        /// <summary> 
        /// List转成json 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="list"></param> 
        /// <returns></returns> 
        public static string ListToJson<T>(IList<T> list)
        {
            object obj = list[0];
            return ListToJson<T>(list, obj.GetType().Name);
        }
        /// <summary> 
        /// 对象转换为Json字符串 
        /// </summary> 
        /// <param name="jsonObject">对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                string value = string.Empty;
                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                {
                    value = "'" + objectValue.ToString() + "'";
                }
                else if (objectValue is string)
                {
                    value = "'" + ToJson(objectValue.ToString()) + "'";
                }
                else if (objectValue is IEnumerable)
                {
                    value = ToJson((IEnumerable)objectValue);
                }
                else
                {
                    value = ToJson(objectValue.ToString());
                }
                jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "}";
        }
        /// <summary> 
        /// 对象集合转换Json 
        /// </summary> 
        /// <param name="array">集合对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString += ToJson(item) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            return jsonString + "]";
        }
        /// <summary> 
        /// 普通集合转换Json 
        /// </summary> 
        /// <param name="array">集合对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToArrayString(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString = ToJson(item.ToString()) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        /// <summary> 
        /// Datatable转换为Json 
        /// </summary> 
        /// <param name="table">Datatable对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();

            if (dt.Rows.Count == 0)
            {
                jsonString.Append("[{}]");
                return jsonString.ToString();
            }

            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        /// <summary> 
        /// DataTable转成Json 
        /// </summary> 
        /// <param name="jsonName"></param> 
        /// <param name="dt"></param> 
        /// <returns></returns> 
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        /// <summary> 
        /// DataReader转换为Json 
        /// </summary> 
        /// <param name="dataReader">DataReader对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DbDataReader dataReader)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            while (dataReader.Read())
            {
                jsonString.Append("{");
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    Type type = dataReader.GetFieldType(i);
                    string strKey = dataReader.GetName(i);
                    string strValue = dataReader[i].ToString();
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (i < dataReader.FieldCount - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            dataReader.Close();
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        /// <summary> 
        /// DataSet转换为Json (加表名)
        /// </summary> 
        /// <param name="dataSet">DataSet对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                //jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
                jsonString += "\"" + table.TableName + "\":" + ToJsonStr(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        /// <summary> 
        /// DataSet转换为Json (加data)
        /// </summary> 
        /// <param name="dataSet">DataSet对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJsonData(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                //jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
                jsonString += "\"" + "data" + "\":" + ToJsonStr(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        /// <summary> 
        /// DataSet转换为Json (加data加分页)
        /// </summary> 
        /// <param name="dataSet">DataSet对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJsonDatas(DataSet dataSet, int shu)
        {
            string jsonString = "{\"draw\":1,\"total\":" + shu + ",\"total\":" + shu + ",";
            foreach (DataTable table in dataSet.Tables)
            {
                //jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
                jsonString += "\"" + "data" + "\":" + ToJsonStr(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        #region  
        /// <summary> 
        /// DataSet转换为Json (不加data)
        /// </summary> 
        /// <param name="dataSet">DataSet对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJsonStr(DataSet dataSet)
        {
            //string jsonString = "{";
            string jsonString = "";
            foreach (DataTable table in dataSet.Tables)
            {
                //jsonString += "\"" + table.TableName + "\":" + ToJsonStr(table) + ",";
                jsonString += "" + ToJsonStr(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            //return jsonString + "}";
            return jsonString;

        }
        /// <summary> 
        /// Datatable转换为Json  +修改删除按钮
        /// </summary> 
        /// <param name="table">Datatable对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJsonStr(DataTable dt)
        {

            StringBuilder jsonString = new StringBuilder();

            if (dt.Rows.Count == 0)
            {
                jsonString.Append("[{}]");
                return jsonString.ToString();
            }
            string idValue = "";
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();

                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                    //if (strKey == "ID")
                    //{
                    //    idValue = strValue;
                    //    jsonString.Append("\"CaoZuo\":\"<a data-toggle='modal' href='jQ_DataTable.aspx#modal-form' onclick='Update(this)' name='" + idValue + "'><span class=' fa fa-edit m-r-xs'></span>修改</a><a data-toggle='modal' onclick='Del(this)' id='shanchu' name='" + idValue + "'><span class=' fa fa-remove m-r-xs'></span>删除</a>\",");
                    //}
                }

                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        #endregion
        /// <summary> 
        /// 过滤特殊字符 
        /// </summary> 
        /// <param name="s"></param> 
        /// <returns></returns> 
        private static string String2Json(String s)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];

                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    //sb.Append(""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    //sb.Append(""); break;
                    case '/':
                        sb.Append("\\/"); break;
                    //sb.Append("-"); break;
                    case '\b':
                        //sb.Append("\\b"); break;
                        sb.Append(""); break;
                    case '\f':
                        //sb.Append("\\f"); break;
                        sb.Append(""); break;
                    case '\n':
                        //sb.Append("\\n"); break;
                        sb.Append(""); break;
                    case '\r':
                        //sb.Append("\\r"); break;
                        sb.Append(""); break;
                    case '\t':
                        //sb.Append("\\t"); break;
                        sb.Append(""); break;
                    case ' ':
                        sb.Append(""); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
        /// <summary> 
        /// 格式化字符型、日期型、布尔型 
        /// </summary> 
        /// <param name="str"></param> 
        /// <param name="type"></param> 
        /// <returns></returns> 
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                if (str != "")
                {
                    str = "\"" + Convert.ToDateTime(str).ToString() + "\"";
                }
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }

            if (str.Length == 0)
                str = "\"\"";

            return str;
        }
        /// <summary>
        /// 固定datable 数据转换为数据表
        /// </summary>
        /// <param name="dt"> 数据表</param>
        /// <param name="type">转换类型，1无模块方式，2模块方式</param>
        /// <returns></returns>
        public static string ToJsonmenu(DataTable dt, string typemode)
        {
            StringBuilder jsonString = new StringBuilder();

            if (dt.Rows.Count == 0)
            {
                jsonString.Append("[{}]");
                return jsonString.ToString();
            }

            jsonString.Append("[");
            DataRow[] dr = dt.Select("menulever ='1'");
            if (dr.Length > 0)
            {

                for (int i = 0; i < dr.Length; i++)
                {
                    jsonString.Append("{ text: '" + dr[i]["name"].ToString() + "',isexpand:false, ");
                    DataRow[] drtwo = dt.Select("upid ='" + dr[i]["upid"].ToString() + "'");
                    if (drtwo.Length > 0)
                    {
                        jsonString.Append(" children:  [ ");
                        for (int j = 0; j < drtwo.Length; j++)
                        {
                            jsonString.Append(" children:  [ {url:\"" + drtwo[j]["address"].ToString() + "\",text:\"" + drtwo[j]["name"].ToString() + "\"} ");
                        }
                    }
                    else
                    {
                        jsonString.Append(" }, ");
                    }
                }

            }
            else
            {
                DataRow[] dr2 = dt.Select("menulever ='2");
                if (dr2.Length > 0)
                {

                }
                else
                {
                    DataRow[] dr3 = dt.Select("menulever ='3");
                    if (dr3.Length > 0)
                    {

                    }
                }
            }
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        /// <summary>
        /// List分页Json
        /// </summary>
        /// <param name="list">list数据</param>
        /// <param name="start">开始条数</param>
        /// <param name="limit">每页多少条</param>
        /// <returns></returns>
        public static string ListToJsonAddFenYe<T>(IList<T> list, int start, int limit)
        {
            int shu = list.Count;
            int xunhuanshu = 0;
            List<T> returnlist = new List<T>();
            if (start + limit > shu)
            {
                xunhuanshu = shu;
            }
            else
            {
                xunhuanshu = start + limit;
            }
            for (int i = start; i < xunhuanshu; i++)
            {
                returnlist.Add(list[i]);
            }
            JsonSerializerSettings jsSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            string returnjson = JsonConvert.SerializeObject(returnlist, jsSettings);
            string jsonString = "{\"draw\":1,\"total\":" + list.Count + ",\"total\":" + list.Count + ","; 
            jsonString += "\"" + "data" + "\":" + "" + returnjson + "" + ",";
            jsonString = jsonString.TrimEnd(',');
            jsonString += "}";
            return jsonString;
        }
        /// <summary>
        /// 将实体类序列化为JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        static public string SerializeJSON<T>(IList<T> list, int start, int limit)
        {
            int shu = list.Count;
            int xunhuanshu = 0;
            List<T> returnlist = new List<T>();
            if (start + limit > shu)
            {
                xunhuanshu = shu;
            }
            else
            {
                xunhuanshu = start + limit;
            }
            for (int i = start; i < xunhuanshu; i++)
            {
                returnlist.Add(list[i]);
            }
            StringBuilder Json = new StringBuilder();
            
            if (returnlist.Count > 0)
            {
                JsonSerializerSettings jsSettings = new JsonSerializerSettings();
                jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                Json.Append( Newtonsoft.Json.JsonConvert.SerializeObject(returnlist, jsSettings));
            }
            
            string returnjson = Json.ToString();
            string jsonString = "{\"draw\":1,\"total\":" + list.Count + ",\"total\":" + list.Count + ",";
            jsonString += "\"" + "data" + "\":" + "" + returnjson + "" + ",";
            jsonString = jsonString.TrimEnd(',');
            jsonString += "}";
            return jsonString;
            //string s= Newtonsoft.Json.JsonConvert.SerializeObject(list);
            //string jsonString = "{\"draw\":1,\"total\":" + list.Count + ",\"total\":" + list.Count + ",";
            //jsonString += "\"" + "data" + "\":" + "" + s + "" + ",";
            //jsonString = jsonString.TrimEnd(',');
            //jsonString += "}";
            //return jsonString;
        }
    }


}